/**
 * @Title TODO
 * @Description  TODO
 * @Company ztesoft
 * @ClassName FastDFSUpUtil.java
 * @author  陈浩良
 * @date  2018年5月7日 上午11:03:47
 * @UpdateUser Administrator
 * @Version 0.1
 */
package com.zros.common.util.fastDFS;


import com.zros.common.util.StringUtil;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;

/**
 * @ClassName FastDFSUpUtil
 * @Description TODO
 * @author lvkai
 * @date 2018年5月7日 上午11:03:47
 */
public class FastDFSUpUtil {

	private static Logger logger = LoggerFactory.getLogger(FastDFSUpUtil.class);

	/*@Autowired
	private IAttrSpecService attrSpecService;*/
	private String serverIP = "127.0.0.1";
	private String portUpload = "";
	private String serverOutIP = "127.0.0.1";
	private String portDown = "";
	/**
	 *
	 * @Description 上传文件
	 * @Author lvkai
	 * @date 2020-4-18 18:51:21
	 * @param file
	 * @param uploadFileName
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(File file, String uploadFileName) throws Exception {
		if (file == null) {
			return null;
		}
		//byte[] fileBuff = FileUtils.readFileToByteArray(file);
		long fileLength = file.length();
		InputStream inputStream = null;
		byte[] fileBuff = null;

		try {
			inputStream = new FileInputStream(file);
			fileBuff = getFileBuffer(inputStream, fileLength);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return send(uploadFileName, fileBuff);
	}

	/**
	 *
	 * @Description 上传文件
	 * @Author lvkai
	 * @date 2020-4-18 18:51:33
	 * @param file
	 * @param uploadFileName
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(MultipartFile file, String uploadFileName) throws Exception {

		if (file == null) {
			return null;
		}
		long fileLength = file.getSize();
		InputStream inputStream = null;
		byte[] fileBuff = null;

		try {
			inputStream = file.getInputStream();
			fileBuff = getFileBuffer(inputStream, fileLength);
			//fileBuff = FileCopyUtils.copyToByteArray(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return send(uploadFileName, fileBuff);
	}

	public String uploadFile(String uploadFileName, byte[] fileBuff) throws Exception{

		return send(uploadFileName,fileBuff);
	}

	/**
	 *
	 * @Description 上传方法体
	 * @Author lvkai
	 * @date 2020-4-18 18:51:41
	 * @param uploadFileName
	 * @param fileBuff
	 * @return
	 * @throws Exception
	 */
	/*private String send(String uploadFileName, byte[] fileBuff) throws Exception {
		if (fileBuff == null) {
			return null;
		}

		String fileExtName = "";
		if (uploadFileName.contains(".")) {
			fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
		} else {
			logger.info("文件命名不合法！");
			return null;
		}



		initClientGlobal(serverIP, Integer.parseInt(portUpload));

		try {
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			StorageClient1 client = new StorageClient1(trackerServer, storageServer);
			String upPath = null;
			upPath = client.upload_file1(fileBuff, fileExtName, null);
			trackerServer.close();
			return upPath;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}*/

	/**
	 *
	 * @Description 上传方法体
	 * @Author lvkai
	 * @date 2020-4-18 18:51:49
	 * @param uploadFileName
	 * @param fileBuff
	 * @return
	 * @throws Exception
	 */
	private String send(String uploadFileName, byte[] fileBuff) throws Exception {
		if (fileBuff == null) {
			return null;
		}

		String fileExtName = "";
		if (uploadFileName.contains(".")) {
			fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
		} else {
			logger.info("文件命名不合法！");
			return null;
		}

		// 读取FastDfs配置信息
		/*Map<String, Object> fastDfsConf = initParams(null);

		String serverIP = StringUtil.getStrForMap(fastDfsConf, "serverIP");
		int portUpload = Integer.parseInt(StringUtil.getStrForMap(fastDfsConf, "portUpload"));*/

		initClientGlobal(serverIP, Integer.parseInt(portUpload));
		//initClientGlobal("192.168.8.3", 22122);

		try {
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			//	StorageServer storageServer = tracker.getStoreStorage(trackerServer);
			StorageServer storageServer = null;
			StorageClient1 client = new StorageClient1(trackerServer, storageServer);
			String upPath = null;
			upPath = client.upload_file1(fileBuff, fileExtName, null);

			trackerServer.close();


			upPath = "http://" + serverOutIP + ":" + portDown + "/" + upPath;
			//upPath = "http://192.168.8.3:" + portDown + "/" + upPath;
			return upPath;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 *
	 * @Description 下载文件
	 * @Author lvkai
	 * @date 2020-4-18 18:51:56
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public  byte[] downloadFile(String path) throws Exception {
		if (StringUtil.isEmpty(path)) {
			return null;
		}
		// 读取FastDfs配置信息


		String head = "http://" + serverOutIP + ":" + portDown + "/";
		path = path.replace(head, "");
		String group = path.substring(0, path.indexOf("/"));
		path = path.substring(path.indexOf("/") + 1);

		// 初始化，这里注意不能传递下载的端口，因为fastdfs服务配置文件已做映射
		initClientGlobal(serverOutIP, Integer.parseInt(portUpload));
		//initClientGlobal("192.168.8.3", 22122);
		TrackerClient tracker = new TrackerClient();
		TrackerServer trackerServer = tracker.getConnection();
		StorageServer storageServer = tracker.getStoreStorage(trackerServer);
		StorageClient client = new StorageClient(trackerServer, storageServer);
		byte[]	fileByte = client.download_file(group, path);
		trackerServer.close();
		return fileByte;
	}

	/**
	 *
	 * @Description 初始化ClientGlobal
	 * @Author lvkai
	 * @date 2020-4-18 18:52:05
	 * @param serverIP
	 * @param port
	 */
	private void initClientGlobal(String serverIP, int port) {
		InetSocketAddress[] trackerServers = new InetSocketAddress[1];
		trackerServers[0] = new InetSocketAddress(serverIP, port);
		ClientGlobal.setG_tracker_group(new TrackerGroup(trackerServers));
		ClientGlobal.setG_connect_timeout(20000);
		ClientGlobal.setG_network_timeout(30000);
		ClientGlobal.setG_anti_steal_token(false);
		ClientGlobal.setG_charset("ISO-8859-1");
		ClientGlobal.setG_secret_key(null);
	}



	/**
	 *
	 * @Description 读取文件流，返回字节数组  ,大文件处理有问题(byte[] fileBuffer = new byte[(int) fileLength])
	 * @Author lvkai
	 * @date 2020-4-18 18:52:15
	 * @param inStream
	 * @param fileLength
	 * @return
	 * @throws IOException
	 */
	private byte[] getFileBuffer(InputStream inStream, long fileLength) throws IOException {

		byte[] buffer = new byte[256 * 1024];
		byte[] fileBuffer = new byte[(int) fileLength];
		int count = 0;
		int length = 0;

		while ((length = inStream.read(buffer)) != -1) {
			for (int i = 0; i < length; ++i) {
				fileBuffer[count + i] = buffer[i];
			}
			count += length;
		}
		return fileBuffer;
	}

	/*** 获取fdfs参数  *******************/
	/*private Map<String, Object> initParams(IAttrSpecService attrSpecServiceL) throws Exception {
		Map<String, Object> qryParams = new HashMap<>();
		qryParams.put("attrSpecCode", "FASTDFS_PARAMS");
		qryParams.put("attrSpecType", "1000");

		Map<String, Object> resultMap = new HashMap<>();
		if(attrSpecServiceL != null){
			resultMap = attrSpecServiceL.qryAttrValueByCode(qryParams);
		}else{
			IAttrSpecService attrSpecService = SpringUtil.getBean("attrSpecService");
			resultMap = attrSpecService.qryAttrValueByCode(qryParams);
		}

		List<Map<String, Object>> attrValues = (List<Map<String, Object>>) resultMap.get(ConstantUtil.JSON_BODY);
		if (null == attrValues || attrValues.size() == 0) {
			throw new Exception("数据库静态数据缺少FastDfs必须参数！");
		}

		//		AttrValue attrValue = attrValues.get(0);
		//		String attrValueCode = attrValue.getAttrValueCode();
		Map<String, Object> map = attrValues.get(0);
		String attrValueCode = (String) map.get("attrValueCode");
		Map<String, Object> fastDfsParamMap = JsonUtil.jsonStrToMap(attrValueCode);
		boolean flag = ReqJsonStrCheckUtil.checkParamEmpty("serverIP,portUpload,serverOutIP,portDown", fastDfsParamMap);
		if (!flag) {
			throw new Exception("静态数据缺少FastDfs必须参数！");
		}
		return fastDfsParamMap;
	}*/
}
